package com.hqyj.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hqyj.config.SmsConfig;
import com.hqyj.dao.PowerDao;
import com.hqyj.pojo.MyNode;
import com.hqyj.pojo.ResultVo;
import com.hqyj.service.UserInfoService;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.sms.v20210111.SmsClient;
import com.tencentcloudapi.sms.v20210111.models.SendSmsRequest;
import com.tencentcloudapi.sms.v20210111.models.SendSmsResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @Description
 * @Autor 伍军
 * @Date 2022/9/22 14:08
 * @Version 1.0
 **/
@Service
public class UserInfoServiceImpl implements UserInfoService {

    //注入邮件发送服务类
    @Autowired
    JavaMailSender javaMailSender;
    //获取发件人邮箱
    @Value("${spring.mail.username}")
    private String fromEmail;

    //注入短信发送服务类
     @Autowired
     SmsClient smsClient;
     //注入腾讯配置类
     @Autowired
     SmsConfig smsConfig;

     @Resource
     PowerDao powerDao;

    //主任redis
    @Autowired
    RedisTemplate<String,Object> redisTemplate;

    @Override
    public ResultVo sendCode(String email) {
        ResultVo rv = new ResultVo();
        try{

        //创建信封对象
        SimpleMailMessage message = new SimpleMailMessage();
        //收件人
        message.setTo(email);
        //发件人
        message.setFrom(fromEmail);
        //邮件标题
        message.setSubject("xxx公司验证码");
        //邮件正文
        Random rd = new Random();
        String code = rd.nextInt(10000)+"";
        message.setText("你的验证码是:"+code);
        //发送邮件
        javaMailSender.send(message);
        //存入redis缓存中2分钟s
        String key ="code:"+email;
        redisTemplate.opsForValue().set(key,code,2, TimeUnit.MINUTES);
        rv.setSuccess(true);
        rv.setInfo("发送成功");
        }catch (Exception e){
            e.printStackTrace();
            rv.setInfo("发送失败");
        }
        return rv;
    }

    @Override
    public ResultVo emailLogin(String email, String code) {
        ResultVo rv  =new ResultVo();
        //判断验证码是否失效
        String key ="code:"+email;
        Object c = redisTemplate.opsForValue().get(key);
        if(c==null){
            rv.setInfo("验证码超过1分钟，失效了");
        }else{
            if(c.equals(code)){
                rv.setSuccess(true);
                rv.setInfo("允许登录");
            }else{
                rv.setInfo("验证码输入不正确");
            }
        }
        return rv;
    }

    @Override
    public ResultVo sendSmsCode(String phone) {
        ResultVo rv = new ResultVo();
        //创建短信内容对象
        SendSmsRequest request = new SendSmsRequest();
        //接收人手机号
        String p[] = {phone};
        request.setPhoneNumberSet(p);
        //短信模板ID
        request.setTemplateId(smsConfig.getSmsTempId());
        //短信SdkID
        request.setSmsSdkAppId(smsConfig.getSmsSdk());
        //短信签名
        request.setSignName(smsConfig.getSmsName());
        //短信验证码
        Random rd = new Random();
        String code = rd.nextInt(10000)+"";
        String c[] ={code};
        request.setTemplateParamSet(c);
        //发送短信
        try {
            SendSmsResponse res =smsClient.SendSms(request);
            System.out.println(SendSmsResponse.toJsonString(res));
            //把json格式字符串转换成map类型
            ObjectMapper mapper = new ObjectMapper();
            try {
                Map<String,Object> map = mapper.readValue(SendSmsResponse.toJsonString(res), Map.class);
                List<HashMap<String,Object>> list =(List<HashMap<String,Object>>)map.get("SendStatusSet");
                if(list.get(0).get("Code").equals("Ok")){
                    rv.setSuccess(true);
                    rv.setInfo("发送成功");
                }

            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }

        } catch (TencentCloudSDKException e) {
            e.printStackTrace();
        }
        return rv;
    }

    @Override
    public ResultVo queryByName(String name) {
        ResultVo rv = new ResultVo();
        List<MyNode> list = powerDao.queryByName(name);
        //构建树形集合
        List<MyNode> listPower = new LinkedList<>();
        if(list.size()==0){
            rv.setInfo("没有权限");
            return rv;
        }
        for(MyNode n:list){
            //查找一级菜单
            if(n.getParentId()==0){
                //创建一级菜单的子菜单集合
                List<MyNode> listChildren = new LinkedList<>();
                //查找一级菜单的子菜单
                for(MyNode nn:list){
                    if(nn.getParentId()==n.getNodeId()){
                        listChildren.add(nn);
                    }
                }
                //添加子菜单
                n.setChildren(listChildren);
                listPower.add(n);
            }
        }
        rv.setSuccess(true);
        rv.setData(listPower);
        return rv;
    }
}
